from django.shortcuts import render,reverse
from django.http import HttpResponse,JsonResponse
from django.contrib.auth.hashers import make_password,check_password
from .. models import Users
import random,time,os
from web import settings
from django.core.paginator import Paginator
from django.db.models import Q

# Create your views here.

#后台图书会员
def index(request):

    #查询所有会员数据
    data=Users.objects.filter()

    #接受搜索条件
    selecttype=request.GET.get('selecttype',None)
    keywords=request.GET.get('keywords',None)
    if selecttype:
        #有搜索条件
        if selecttype == 'all':
            #按照多字段进行搜索
            data=data.filter(Q(phone__contains=keywords)|Q(nickname__contains=keywords)|Q(sex__contains=keywords)|Q(usertype__contains=keywords))

            #select * from users where name like '%a%' or phone like '%a%'
        else:
            serdata={f"{selecttype}__contains":keywords}
            data=data.filter(**serdata)


    #实例化分页对象，参数1，数据集；参数2，每页显示的条数
    p=Paginator(data,10)

    #接收当前的页码数
    inx_p=request.GET.get('page',1)

    #获取当前页的数据
    # userlist=p.page(1)
    userlist=p.get_page(inx_p)

    #分配数据
    content={'data':userlist,'contacts':userlist}

    #加载模板
    return render(request,'myadmin/users/index.html',content)

#会员添加
def add(request):
    return render(request, 'myadmin/users/add.html')

#执行会员添加
def insert(request):
    #接受表单提交数据
    data=request.POST.dict()
    data.pop('csrfmiddlewaretoken')

    #密码加密
    data['password']=make_password(data['password'],None,'pbkdf2_sha256')

    try:
        # 检测是否上传了头像
        file=request.FILES.get('face',None)
        if file:
            #上传了头像
            data['face']=imgupload(file)
        else:
            data.pop('face')

        #进行数据的添加
        obj=Users(**data)
        obj.save()

        url = reverse('myadmin_users_index')
        return HttpResponse(f'<script>alert("会员添加成功");location.href="{url}"</script>')
    except:
        url = reverse('myadmin_users_add')
        return HttpResponse(f'<script>alert("会员添加失败");location.href="{url}"</script>')


#执行会员删除
def delete(request):
    try:
        id=request.GET.get('id')
        obj=Users.objects.get(id=id)
        #判断当前用户是否有上传的图像
        try:
            if 'uploads' in obj.face:
                #删除
                os.remove('.'+obj.face)
        except:
            return JsonResponse({'code': 1, 'msg': '图片未能删除，删除失败'})

        #删除用户失败
        obj.delete()
        return JsonResponse({'code':0,'msg':'删除成功'})
    except:
        return JsonResponse({'code':1,'msg':'删除失败'})



#执行会员修改
def edit(request):
    #获取id
    id=request.GET.get('id')
    # 通过id获取会员信息
    obj=Users.objects.get(id=id)
    return render(request,'myadmin/users/edit.html',{'obj':obj})

def update(request):
    data = request.POST.dict()
    data.pop('csrfmiddlewaretoken')


    #判断当前密码是否更新
    if data['password'] != data['old_password']:
        data['password'] = make_password(data['password'], None, 'pbkdf2_sha256')
    else:
        data['password']=data['old_password']
    data.pop('old_password')


    # 判断当前是否更新图片
    file = request.FILES.get('face', None)
    print(file)
    if file:
        # 上传了新的图片
        filename = imgupload(file)
        if 'uploads' in data['old_face']:
            # 删除原来的图片信息
            os.remove('.' + data['old_face'])
        data['face'] = filename

    else:
        # 没有上传图片
        data['face'] = data['old_face']

    # 删除原来的图片信息
    data.pop('old_face')

    try:
    # 更新操作
        Users.objects.filter(id=data['id']).update(**data)
        url = reverse('myadmin_users_index')
        return HttpResponse('<script>alert("更新成功");location.href="' + url + '";</script>')
    except:
        url = reverse('myadmin_users_edit')
        id = str(data['id'])
        return HttpResponse(f'<script>alert("更新失败");location.href="{url}?id={id}";</script>')


#封装图片上传方法
def imgupload(file):
    try:
        filename=str(random.randint(10000,99999)+time.time())+'.'+file.name.split('.').pop()
        with open(f'./static/uploads/{filename}','wb+') as fp:
            fp.write(file.read())

        return f'/static/uploads/{filename}'
    except:
        return False